package com.tang.sharding.schedule.task.jdbc;

import com.tang.sharding.ShardProperties;
import com.tang.sharding.schedule.task.AbstractRunnableTask;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

/**
 * @author Tang
 * @classname AbstractJdbcRunnableTask
 * @description [ jdbc工作 ]
 * @date 2021/8/1 17:00
 */
@Slf4j
public abstract class AbstractJdbcRunnableTask extends AbstractRunnableTask {

    @Getter
    protected ShardProperties.TableRule tableRule;

    protected String sql;

    protected JdbcManager jdbcManager;

    public AbstractJdbcRunnableTask(String taskId, JdbcManager jdbcManager,
                                    ShardProperties.TableRule tableRule) {
        super(taskId);
        this.tableRule = tableRule;
        this.jdbcManager = jdbcManager;
    }

    @Override
    protected void doWork() {
        // new table name
        String newTableName = getTableName(tableRule.getLogicTable());
        // new sql
        getJdbcSql(newTableName);
        if (StringUtils.isNotEmpty(this.sql) && !jdbcManager.checkTable(newTableName)) {
            jdbcManager.createTable(newTableName, this.sql);
        }
    }

    /**
     * get jdbc
     *
     * @param newTableName
     */
    private void getJdbcSql(String newTableName) {
        String logicTable = tableRule.getLogicTable();
        this.sql = this.jdbcManager.getTableSql(logicTable, newTableName);
    }

    /**
     * get table name
     *
     * @param logicTable
     * @return
     */
    protected abstract String getTableName(String logicTable);
}